const express = require('express')
const path = require('path')
const { put } = require('./utils/oss')
const multer = require('multer')
const app = express()
const router = express.Router()

// const multerMiddler = multer({ dest: '/uploads' })
const storage = multer.diskStorage({
  destination: 'uploads',
  filename(req, file, cb) {
    const filenameArr = file.originalname.split('.')
    cb(null, Date.now() + '.' + filenameArr[filenameArr.length - 1])
  }
})
const upload = multer({ storage })

router.post('/upload', upload.single('avatar') ,async (req, res, next) => {
  try {
    console.log(req.file)
    const { filename } = req.file
    // 生成存储在数据的头像/文件 url
    const avatarUrl = `http://localhost:3000/${filename}`
    res.send({ avatarUrl })
  } catch(err) {
    console.error('上传文件报错：', err)
  }
})

router.post('/oss', upload.single('file'), async (req, res ,next) => {
  try {
    const { filename } = req.file
    const result = await put(filename, path.resolve(__dirname, `../uploads/${filename}`))
    console.log('oss返回: ', result)
    if(result?.status === 200) {
      res.send(result)
    } else {
      res.send({ code: 0, message: '上传报错！' })
    }
  } catch(err) {
    console.err('oss报错: ', err)
  }
})

app.use(express.json())
app.use(express.static(path.resolve(__dirname, '../uploads')))
app.use('', router)
app.listen(3000, () => {
  console.log('服务器在端口 3000 启动 ~')
})